package leetcode.editor.cn.q1_300.q;

/**
 * @author qidi
 * @date 2021-11-01 17:15:14
 */
class Q0019_RemoveNthNodeFromEndOfList {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast = head;
            ListNode slow = null;
            ListNode pre = null;

            while (fast != null) {
                fast = fast.next;
                n--;

                if (n == 0) {
                    slow = head;
                    continue;
                }
                if (slow != null) {
                    pre = slow;
                    slow = slow.next;
                }
            }
            if (pre == null) {
                // 说明删除的是头结点
                return head.next;
            } else {
                pre.next = slow.next;
            }

            return head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0019_RemoveNthNodeFromEndOfList().new Solution();

        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        solution.removeNthFromEnd(head, 1);
    }
}